<?php
namespace app\admin\model;
use think\Model;

class Admin extends Model
{

    /**
     * 登录验证
     */
    public function login($username, $password){
        //查询帐号
        $map=[['account','=',$username],['hide_flag','=',0]];
        $r = $this->where($map)->find();
        if(!$r){
            $this->error = '该账号不存在！';
            return false;
        }
        if($r['state']==0){
            $this->error = '该账号被禁用！';
            return false;
        }

        $password = md5($password);
        if($r['password']!=$password){
            $this->error = '密码不正确！';
            return false;
        }
        $id=$r['id'];

        $ip = request()->ip();
        define('NOW_TIME',time());
        $condtion['lastloginip']=$ip;
        $condtion['lastlogintime']=NOW_TIME;
        if(!empty($r['lastloginlog'])){
            $log = string2array($r['lastloginlog']);
            array_unshift($log, NOW_TIME.'|'.$ip);
            count($log)>3 && array_pop($log);
        }else{
            $log = array(NOW_TIME.'|'.$ip);
        }
        $condtion['lastloginlog']=var_export($log,true);
        $condtion['logincount']=['inc',1];
        $this->save($condtion,['id'=>$id]);

        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $r['id'],
            'account'         => $username,
            'last_login_time' => NOW_TIME,
        );

        $save_pre  =config("common.admin_login_save_pre");
        $save_type =config("common.admin_login_save");
        if(1==$save_type){
            session($save_pre.'_auth', $auth);
            session($save_pre.'_auth_sign', data_auth_sign($auth));
        }else{
            $time=86400;
            cookie($save_pre.'_auth', $auth,$time);//登录用户的账号，id,登录时间
            cookie($save_pre.'_auth_sign', data_auth_sign($auth),$time); //登录校验码
        }

        return true;
    }


}
